<template>
  <div class="grLayout rtmAnalyse">
    <div class="layout-container">
      <!-- 查询条件区域 -->
      <div class="query-conditions">
        <div class="title">
          <img
            src="@/assets/images/titleIcon.png"
            alt
            style="width: 16px; height: 16px; margin-right: 5px"
          />
          <span>查询条件</span>
        </div>
        <div class="conditions">
          <a-form
            ref="formRef"
            :hideRequiredMark="true"
            layout="inline"
            :model="formSearchProps?.formState"
            name="basic"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 16 }"
            autocomplete="off"
          >
            <a-form-item label="镇" >
              <a-select  style="width:200px" v-model:value="formSearchProps.formState.town">
                <a-select-option
                  v-for="(item,index) in state.townList"
                  :key="index"
                  :value="item.value">{{ item.label }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="年" >
              <a-select  style="width:200px"  v-model:value="formSearchProps.formState.year">
                <a-select-option
                  v-for="(item,index) in state.years"
                  :key="index"
                  :value="item.value">{{ item.label }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="时间段" >
              <a-range-picker
                style="width: 280px"
                v-model:value="formSearchProps.formState.timeRange"
                format="YYYY-MM-DD"
                :placeholder="['开始日期', '结束日期']"
              />
            </a-form-item>
          </a-form>
          <div class="resqy">
            <a-button type="primary" @click="handleQuery" :loading="state.loading">查询</a-button>
            <a-button @click="handleReset" style="margin-left: 12px">重置</a-button>
          </div>
        </div>
      </div>

      <!-- 中间内容区域 -->
      <div class="middle-content">
        <!-- 左侧卡片区域 -->
        <div class="left-card">
          <div class="station-list-header">
            <img
              src="@/assets/images/titleIcon.png"
              alt
              style="width: 16px; height: 16px; margin-right: 5px"
            />
            <span>发送记录统计</span>
          </div>
          <div class="stats-container">
            <!-- 电话语音统计 -->
            <div class="stat-card phone-stats">
              <div class="stat-header">
                <div class="stat-icon">
                  <svg viewBox="0 0 24 24" width="24" height="24" fill="#1890ff">
                    <path d="M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"/>
                  </svg>
                </div>
                <h3>电话语音统计</h3>
              </div>
              <div class="stat-content">
                <div class="stat-item">
                  <span class="label">总数</span>
                  <span class="value highlight">{{ state.total1 }}条</span>
                </div>
                <div class="stat-item success">
                  <span class="label">成功总数</span>
                  <span class="value success-text">{{ state.total_success1 }}条</span>
                </div>
                <div class="stat-item error">
                  <span class="label">失败总数</span>
                  <span class="value error-text" @click="handleViewFail(1)">{{ state.total_fail1 }}条</span>
                </div>
              </div>
            </div>

            <!-- 短信发送统计 -->
            <div class="stat-card message-stats">
              <div class="stat-header">
                <div class="stat-icon">
                  <svg viewBox="0 0 24 24" width="24" height="24" fill="#52c41a">
                    <path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"/>
                  </svg>
                </div>
                <h3>短信发送统计</h3>
              </div>
              <div class="stat-content">
                <div class="stat-item">
                  <span class="label">发送总数</span>
                  <span class="value highlight">{{ state.total2 }}条</span>
                </div>
                <div class="stat-item success">
                  <span class="label">成功总数</span>
                  <span class="value success-text">{{ state.total_success2 }}条</span>
                </div>
                <div class="stat-item error">
                  <span class="label">失败总数</span>
                  <span class="value error-text" @click="handleViewFail(2)">{{ state.total_fail2 }}条</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧图表区域 -->
        <div class="right-chart">
          <div class="chartContent" ref="chartRefWater"></div>
        </div>
      </div>

      <!-- 底部表格区域 -->
      <div class="table-container">
        <a-table
          class="antdTableInfo"
          :columns="state.tableColumns"
          :data-source="state.tableDataSource"
          :pagination="true"
          size="small"
          bordered
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'tm'">
              {{
                record.tm.replace("T"," ")
              }}
            </template>
            <template v-if="column.dataIndex === 'warnLevel'">
              {{
                record.warnLevel=='1'?'极高风险':"高风险"
              }}
            </template>
            <template v-if="column.dataIndex === 'action'">
              <a-button type="link" size="small" @click="handleView(record)">查看详情</a-button>
            </template>
          </template>
        </a-table>
      </div>
    </div>
    <DetailsModal @register="registerModal" />
    <FailDetailsModal @register="registerModalFail" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import dayjs from "dayjs";
import { useECharts } from "@gui-pkg/hooks";
import setChartOption from "./chartOption";
import {getWarnmsgPage,countNum,countList,findDefaultDate} from "@/api/alerts/warningSendRecords";
import {useModal} from "@gui-pkg/antdcomponents";
import DetailsModal from './DetailsModal';
import FailDetailsModal from './FailDetailsModal';

const [registerModal, { openModal }] = useModal();
const [registerModalFail, { openModal:openModalFail }] = useModal();
const loading = ref(false);
const chartRefWater = ref<HTMLDivElement | null>(null);
const { setOptions: setOptionsWater } = useECharts(chartRefWater as Ref<HTMLDivElement>);
const formRef = ref();
const year = dayjs().format("YYYY");
let yearOptions = [...Array(10)].map((_, i) => ({ value: year - i }));

const state = reactive({
  chartOption: null,
  stationData: null,
  tableDataSource: [],
  total1:0,
  total_success1:0,
  total_fail1:0,
  total2:0,
  total_success2:0,
  total_fail2:0,
  tableColumns: [
    { dataIndex: "tm", title: "发送时间", align: "center" },
    { dataIndex: "stnm", title: "站点", align: "center" },
    { dataIndex: "town", title: "镇", align: "center" },
    { dataIndex: "warnLevel", title: "预警级别", align: "center" },
    { dataIndex: "process2", title: "短信发送记录（成功/总数）", align: "center" },
    { dataIndex: "process1", title: "电话拨打记录（成功/总数）", align: "center" },
    {
      dataIndex: 'action',
      title: '操作',
      align: 'center',
      width: 100,
    },
  ],
  townList: [
    {value: '武穴市', label: '武穴市'},
    {value: '大金镇', label: '大金镇'},
    {value: '四望镇', label: '四望镇'},
    {value: '梅川镇', label: '梅川镇'},
    {value: '花桥镇', label: '花桥镇'},
    {value: '田家镇街道', label: '田家镇街道'},
    {value: '余川镇', label: '余川镇'},
    {value: '大法寺镇', label: '大法寺镇'},
    {value: '刊江街道', label: '刊江街道'},
  ],
  years:[
    {value: '全部', label: '全部'},
    {value: '2025', label: '2025'},
    {value: '2026', label: '2026'},
    {value: '2027', label: '2027'},
    {value: '2028', label: '2028'},
    {value: '2029', label: '2029'},
    {value: '2030', label: '2030'},
  ],
  months:[
    {value: '全部', label: '全部'},
    {value: '01', label: '1月'},
    {value: '02', label: '2月'},
    {value: '03', label: '3月'},
    {value: '04', label: '4月'},
    {value: '05', label: '5月'},
    {value: '06', label: '6月'},
    {value: '07', label: '7月'},
    {value: '08', label: '8月'},
    {value: '09', label: '9月'},
    {value: '10', label: '10月'},
    {value: '11', label: '11月'},
    {value: '12', label: '12月'},
  ]
});

// Query conditions
const formSearchProps = reactive({
  formState: {
    year:"全部",
    town:"武穴市",
    month:"全部",
    timeRange:null
  },
});

// // 查看操作
// const handleView = (record) => {
//   console.log('查看记录:', record);
//   // 这里可以添加查看详情的逻辑，比如打开弹窗、跳转页面等
//   // 例如：打开详情弹窗
//   // state.viewModalVisible = true;
//   // state.currentRecord = record;
// };

// Reset
const handleReset = () => {
  formRef.value.resetFields();
  handleQuery();
};


const handleViewFail= (type) => {

  // 处理时间段参数
  let startDate = '';
  let endDate = '';


  if (formSearchProps.formState.timeRange && formSearchProps.formState.timeRange.length === 2) {
    startDate = formSearchProps.formState.timeRange[0].format('YYYY-MM-DD')+" 00:00:00";
    endDate = formSearchProps.formState.timeRange[1].format('YYYY-MM-DD')+" 23:59:59";
  }

  const params = {
    town: formSearchProps.formState.town,
    year: formSearchProps.formState.year,
    beginTime: startDate,
    endTime: endDate,
    activeTab:type
  };

  openModalFail(true, {
    record: params,
  });
};

const handleQuery = () => {
  formRef.value.validateFields().then(() => {
    getHistoryList();
  });
};

// Get history data
const getHistoryList = async () => {
  // 处理时间段参数
  let startDate = '';
  let endDate = '';

  if (formSearchProps.formState.timeRange && formSearchProps.formState.timeRange.length === 2) {
    startDate = formSearchProps.formState.timeRange[0].format('YYYY-MM-DD')+" 00:00:00";
    endDate = formSearchProps.formState.timeRange[1].format('YYYY-MM-DD')+" 23:59:59";
  }

  const params = {
    town: formSearchProps.formState.town,
    year: formSearchProps.formState.year,
    beginTime: startDate,
    endTime: endDate,
    pageSize: 500,
    pageNum: 1
  };

  const stationData = await getWarnmsgPage(  params);
  state.stationData = stationData.records;
  state.tableDataSource = stationData.records;

  const nums = await countNum(params);

  console.log('---------nums',nums)
  for(let i=0;i<nums.length;i++){
    if(nums[i].log_type=='1'){
      //语音
      state.total1=nums[i].total_num;
      state.total_success1=nums[i].success_num;
      state.total_fail1=state.total1-state.total_success1;
    }else{
      state.total2=nums[i].total_num;
      state.total_success2=nums[i].success_num;
      state.total_fail2=state.total2-state.total_success2;
    }
  }

  const numList = await countList(params);

  console.log('numListnumListnumListnumList0---',numList)
  const chartOption   = setChartOption(numList);
  setOptionsWater(chartOption);
};

const serchData = () => {
  let start = dayjs().subtract(3,"day").format("YYYY-MM-DD");
  let end = dayjs().format("YYYY-MM-DD");
  formSearchProps.formState.time = [start, end];
  formSearchProps.formState.sttp = "PP";
};

const getStcd = async (sttp) => {
  // 实现代码保持不变
};
const handleView = (data)=> {
  openModal(true, {
    record: data,
  });
}
onMounted(async () => {
  const startDateStr = await findDefaultDate();

  let end = dayjs().format("YYYY-MM-DD");
  const startDate = dayjs(startDateStr);
  console.log('----------------------',startDate)
  const endDate = dayjs().format("YYYY-MM-DD");
  formSearchProps.formState.timeRange = [startDate, dayjs(endDate)];
  await handleQuery();

});
</script>

<style lang="less" scoped>
.rtmAnalyse {
  height: 100%;
  padding: 16px;

  .layout-container {
    display: flex;
    flex-direction: column;
    height: 100%;
    background: #fff;
    border-radius: 4px;
    overflow: hidden;
  }

  .query-conditions {
    padding: 16px;
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 16px;

    .title {
      font-size: 16px;
      display: flex;
      align-items: center;
      margin-bottom: 16px;
    }

    .conditions {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .resqy {
        display: flex;
        justify-content: flex-end;
      }
    }
  }

  .middle-content {
    display: flex;
    flex: 1;
    margin-bottom: 16px;
    max-height: 300px;

    .left-card {
      width: 50%;
      padding-right: 8px;
      display: flex;
      flex-direction: column;

      .station-list-header {
        font-size: 16px;
        font-weight: 500;
        display: flex;
        align-items: center;
        padding: 12px 16px;
        border-bottom: 1px solid #f0f0f0;
        background-color: #fafafa;
        margin-bottom: 0;
      }

      .stats-container {
        flex: 1;
        display: flex;
        border: 1px solid #f0f0f0;
        border-top: none;
        overflow: hidden;

        .stat-card {
          flex: 1;
          padding: 16px;
          display: flex;
          flex-direction: column;
          border-right: 1px solid #f0f0f0;

          &:last-child {
            border-right: none;
          }

          .stat-header {
            display: flex;
            align-items: center;
            margin-bottom: 16px;
            padding-bottom: 12px;
            border-bottom: 1px solid #f0f0f0;

            .stat-icon {
              display: flex;
              align-items: center;
              justify-content: center;
              width: 36px;
              height: 36px;
              border-radius: 50%;
              background-color: rgba(24, 144, 255, 0.1);
              margin-right: 12px;

              svg {
                width: 20px;
                height: 20px;
              }
            }

            h3 {
              margin: 0;
              font-size: 16px;
              font-weight: 600;
              color: #262626;
            }
          }

          &.message-stats {
            .stat-header .stat-icon {
              background-color: rgba(82, 196, 26, 0.1);
            }
          }

          .stat-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-around;

            .stat-item {
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: 8px 0;

              .label {
                font-size: 14px;
                color: #595959;
                font-weight: 500;
              }

              .value {
                font-size: 16px;
                font-weight: 600;

                &.highlight {
                  color: #1890ff;
                }

                &.success-text {
                  color: #52c41a;
                }

                &.error-text {
                  color: #f5222d;
                  cursor: pointer;
                }
              }
            }

            .success .value {
              color: #52c41a;
            }

            .error .value {
              color: #f5222d;
            }
          }
        }
      }
    }

    .right-chart {
      width: 50%;
      padding-left: 8px;

      .chartContent {
        width: 100%;
        height: 100%;
        border: 1px solid #f0f0f0;
        border-radius: 2px;
      }
    }
  }

  .table-container {
    flex: none;
    overflow-y: auto;
    border: 1px solid #f0f0f0;
    border-radius: 2px;
    padding: 16px;
    background-color: #fff;
  }
}
</style>
